const express = require('express');
const router = express.Router();
const userController = require('../controllers/userController');
const authMiddleware = require('../middleware/authMiddleware');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

// 配置 multer 存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const uploadPath = path.join(__dirname, '../uploads/avatars');
    // 确保目录存在，multer 会自动创建
    fs.mkdirSync(uploadPath, { recursive: true });
    cb(null, uploadPath);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, req.user.user_id + '-' + uniqueSuffix + path.extname(file.originalname));
  }
});

const upload = multer({ storage: storage });

router.post('/register', userController.register);
router.post('/login', userController.login);
router.post('/default-city', authMiddleware, userController.setDefaultCity);
router.get('/me', authMiddleware, userController.getUserInfo);
router.put('/profile', authMiddleware, userController.updateUserProfile);
router.put('/change-password', authMiddleware, userController.changePassword);
router.post('/upload-avatar', authMiddleware, upload.single('avatar'), userController.uploadAvatar);
router.post('/set-default-city', authMiddleware, userController.setDefaultCity);
router.post('/favorite-city', authMiddleware, userController.addFavoriteCity);
router.get('/favorite-cities', authMiddleware, userController.getFavoriteCities);

module.exports = router;